package com.zesionlee.server.controller

import com.zesionlee.server.entity.FileEntity
import com.zesionlee.server.entity.UploadFileEntity
import com.zesionlee.server.result.Result
import com.zesionlee.server.service.FileService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.web.bind.annotation.*
import java.io.File
import java.io.IOException


@RequestMapping("/file")
@RestController
@CrossOrigin("*")
@Tag(description = "文件处理模块", name = "文件处理模块")
class FileController(val fileService: FileService) {


    @GetMapping("/get-sub")
    @Operation(summary = "获取文件夹子目录")
    fun getList(@RequestParam(value = "sub", required = false) sub: String): Result<List<FileEntity>> {
        val list: List<FileEntity> = fileService.getSubList(sub)
        return Result.success(list)
    }

    @GetMapping("/mkdir")
    @Operation(summary = "新建文件夹")
    fun getMkdir(@RequestParam parent: String, @RequestParam name: String): Result<Unit> {
        if (!File(parent).exists()) return Result.error("父文件夹不存在！")
        try {
            File(parent + File.separator + name).mkdir()
        } catch (e: IOException) {
            return Result.error("新建文件夹失败！")
        }
        return Result.successMsg("新建文件夹成功！")
    }


    @PostMapping("/upload")
    @Operation(summary = "上传文件到指定文件夹")
    fun uploadFile(uploadFileEntity: UploadFileEntity): Result<Unit> {
        fileService.uploadFile(uploadFileEntity)
        return Result.successMsg("上传文件成功！")
    }
}